package cn.codeforfun.interceptor.resolver;

import cn.codeforfun.interceptor.WxMsg;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import static cn.codeforfun.consts.WxConsts.WX_REQUEST_MSG;

@Component
public class WxMsgInterceptor implements HandlerMethodArgumentResolver {
  @Override
  public boolean supportsParameter(MethodParameter parameter) {
    return parameter.getParameterType().isAssignableFrom(WxMpXmlMessage.class)
            && parameter.hasParameterAnnotation(WxMsg.class)
            ;
  }

  @Override
  public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
    WxMpXmlMessage message = null;
    Object attribute = webRequest.getAttribute(WX_REQUEST_MSG, 0);
    if (attribute != null && !"".equals(attribute)) {
      message = WxMpXmlMessage.fromXml((String) attribute);
    }
    return message;
  }
}
